import { string2arrayBuffer } from "./string2arrayBuffer";

export function base64String2arrayBuffer(uri: string) {
  // strip newlines
  uri = uri.replace(/\r?\n/g, "");

  // split the URI up into the "metadata" and the "data" portions
  var firstComma = uri.indexOf(",");
  if (-1 === firstComma || firstComma <= 4) throw new TypeError("malformed data-URI");

  // remove the "data:" scheme and parse the metadata
  var meta = uri.substring(5, firstComma).split(";");

  var base64 = false;
  var charset = "US-ASCII";
  for (var i = 0; i < meta.length; i++) {
    if ("base64" == meta[i]) {
      base64 = true;
    } else if (0 == meta[i].indexOf("charset=")) {
      charset = meta[i].substring(8);
    }
  }

  // get the encoded data portion and decode URI-encoded chars
  var data = unescape(uri.substring(firstComma + 1));

  if (base64) data = atob(data);

  const abuf: Record<string, any> = string2arrayBuffer(data);

  abuf.type = meta[0] || "text/plain";
  abuf.charset = charset;

  return abuf;
}
